package cn.italkcloud.cph.helper;

import cn.italkcloud.cph.constants.enums.PermDataEnum;
import cn.italkcloud.cph.constants.enums.PermViewEnum;
import cn.italkcloud.cph.entity.dto.AccountDTO;
import cn.italkcloud.cph.entity.dto.UserAuthDTO;
import cn.italkcloud.cph.entity.dto.UserDTO;
import cn.italkcloud.cph.utils.JsonUtil;
import cn.italkcloud.cph.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * 用户工具
 * 简化后仅使用本地内存
 *
 * @author dominate
 * @since 2025/3/19
 **/
@Slf4j
public class UserHelper {

    private static final String ACCOUNT_DATA_FILE_PATH = "user/accounts.txt";

    private static final Map<Integer, AccountDTO> USER_DATA = new HashMap<>();
    private static final Map<String, Integer> LOGIN_DATA = new HashMap<>();

    static {
        loadUserData();
    }

    private static void loadUserData() {
        try (InputStream inputStream = UserHelper.class.getClassLoader().getResourceAsStream(ACCOUNT_DATA_FILE_PATH)) {
            if (Objects.isNull(inputStream)) {
                return;
            }
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            StringBuilder data = new StringBuilder();
            try (BufferedReader br = new BufferedReader(reader)) {
                String line;
                while ((line = br.readLine()) != null) {
                    data.append(line);
                }
            }
            System.out.println(data);
            List<AccountDTO> accountList = JsonUtil.parseToList(data.toString(), AccountDTO.class);
            for (AccountDTO account : accountList) {
                USER_DATA.put(account.getId(), account);
                LOGIN_DATA.put(account.getName(), account.getId());
            }
        } catch (Exception e) {
            log.error("初始化账号失败", e);
        }

    }


    public static List<UserDTO> search(String keyword) {
        List<UserDTO> result = new ArrayList<>();
        for (AccountDTO account : USER_DATA.values()) {
            if (account.getName().contains(keyword)) {
                result.add(parseUser(account));
                continue;
            }
            if (account.getAccount().contains(keyword)) {
                result.add(parseUser(account));
                continue;
            }
            if (StringUtil.isNumeric(keyword) && account.getId().equals(Integer.parseInt(keyword))) {
                result.add(parseUser(account));
            }
        }
        return result;
    }


    public static UserDTO parseUser(AccountDTO account) {
        return new UserDTO()
                .setAccount(account.getAccount())
                .setName(account.getName())
                .setAccountId(account.getId());
    }


    public static String getUserName(Integer accountId) {
        if (!USER_DATA.containsKey(accountId)) {
            return "未知账号";
        }
        return USER_DATA.get(accountId).getName();
    }

    public static int findAccount(String name) {
        if (!LOGIN_DATA.containsKey(name)) {
            return 0;
        }
        return LOGIN_DATA.get(name);
    }

    public static UserAuthDTO prepareUser(int accountId) {
        AccountDTO account = USER_DATA.get(accountId);
        UserAuthDTO user = new UserAuthDTO();
        user.setAccountId(account.getId());
        user.setName(account.getName());
        user.setDataPermIds(parsePermIdList(account.getPermData(), PermDataEnum.getIds()));
        user.setViewPermIds(parsePermIdList(account.getPermView(), PermViewEnum.getIds()));
        return user;
    }

    public static boolean checkPassword(int accountId, String password) {
        return USER_DATA.get(accountId).getPassword().equals(password);
    }

    private static List<String> parsePermIdList(List<String> accountPermIds, List<String> permIds) {
        if (accountPermIds.size() == 1 && accountPermIds.get(0).equals("all")) {
            return new ArrayList<>(permIds);
        }
        List<String> pathList = new ArrayList<>();
        for (String permId : accountPermIds) {
            if (!permIds.contains(permId)) {
                continue;
            }
            pathList.add(permId);
        }
        return pathList;
    }


}
